package com.sunseen.capacitormachine.modules.log;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.common.MethodUtil;
import com.sunseen.capacitormachine.commumication.http.HttpUtil;
import com.sunseen.capacitormachine.commumication.http.RestClient;
import com.sunseen.capacitormachine.data.DataUtil;
import com.sunseen.capacitormachine.databinding.FragmentTodayOperateLogBinding;
import com.sunseen.capacitormachine.modules.log.adapter.OperateLogAdapter;
import com.sunseen.capacitormachine.modules.log.bean.UserOperateBean;
import com.sunseen.capacitormachine.modules.log.event.QueryLogEvent;
import com.sunseen.capacitormachine.modules.log.event.RefreshLogListEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Calendar;
import java.util.List;

public class ToDayOperateLogListFragment extends BaseFragment {
    @Override
    protected int setLayout() {
        return R.layout.fragment_today_operate_log;
    }

    private boolean showNullToast = false;

    private long startTime;
    private long endTime;

    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        startTime = MethodUtil.getStartTimeStamp(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
        endTime = MethodUtil.getEndTimeStamp(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH));
    }

    private FragmentTodayOperateLogBinding binding;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        initTime();
        binding = (FragmentTodayOperateLogBinding) viewDataBinding;
        adapter = new OperateLogAdapter(R.layout.layout_item_operate_log);
        binding.todayOperateLogRv.setLayoutManager(new LinearLayoutManager(_mActivity));
        adapter.bindToRecyclerView(binding.todayOperateLogRv);
        adapter.setEnableLoadMore(true);
        adapter.setLoadMoreView(new LogDateLoadMoreView());
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (curPage == lastPage) {
                    if (fragmentShowing) {
                        Toast.makeText(_mActivity, "该日期的操作日志已全部加载", Toast.LENGTH_SHORT).show();
                    }
                    adapter.loadMoreEnd(true);
                } else {
                    queryLogs(startTime, endTime, curPage + 1, false);
                }
            }
        }, binding.todayOperateLogRv);
        adapter.disableLoadMoreIfNotFullPage();
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        queryLogs(startTime, endTime, 1, true);
    }

    private OperateLogAdapter adapter;
    private int lastPage = 0;
    private int curPage = 0;

    private void queryLogs(long startTime, long endTime, int page, boolean refresh) {
        Log.e("test", "queryToDayOperateLogs: " + startTime + " :" + endTime);
        RestClient.builder()
                .url(HttpUtil.OperateLog)
                .params("deviceNo", DataUtil.DeviceNo)
                .params("start_time", startTime)
                .params("end_time", endTime)
                .params("platform", 1)
                .params("userId", 1)
                .params("page", page)
                .success((String response) -> {
                    Log.e("test", "queryLogs: success ");
                    JSONObject rootObj = JSON.parseObject(response);
                    int status = rootObj.getIntValue("status");
                    if (status == 1) {
                        JSONObject dataObj = rootObj.getJSONObject("data");
                        curPage = dataObj.getIntValue("current_page");
                        List<UserOperateBean> operateBeanList = dataObj.getJSONArray("data")
                                .toJavaList(UserOperateBean.class);
                        if (!operateBeanList.isEmpty()) {
                            if (refresh) {
                                adapter.setNewData(operateBeanList);
                                lastPage = dataObj.getIntValue("last_page");
                            } else {
                                adapter.addData(operateBeanList);
                                adapter.loadMoreComplete();
                            }
                        } else {
                            if (showNullToast) {
                                Toast.makeText(_mActivity, "操作日志数据返回为空", Toast.LENGTH_SHORT).show();
                            } else {
                                showNullToast = true;
                            }
                        }
                    } else {
                        Toast.makeText(_mActivity, "操作日志数据返回状态码0", Toast.LENGTH_SHORT).show();
                    }
                })
                .failure(() -> {
                    Toast.makeText(_mActivity, "操作日志数据请求失败", Toast.LENGTH_SHORT).show();
                    Log.e("test", "queryLogs: failure");
                })
                .error((int code, String msg) -> {
                    Toast.makeText(_mActivity, "操作日志数据返回错误:" + msg, Toast.LENGTH_SHORT).show();
                    Log.e("test", "queryLogs: error" + msg);
                })
                .build()
                .get();
    }


    private boolean fragmentShowing = true;

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        fragmentShowing = !hidden;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onRefreshLogList(RefreshLogListEvent event) {
        initTime();
        queryLogs(startTime, endTime, 1, true);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
